<template>
  <div class="login-container">
    <el-row justify="center" align="middle" style="height: 100vh;">
      <el-col :span="24">
        <el-card shadow="always">
          <div class="logo">
            <!--<img src="@/assets/logo.png" alt="Logo" />-->
          </div>
          <h2>欢迎登录后台管理系统</h2>
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="formData.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(formRef)">登录</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { login } from '../api/auth'

const formRef = ref(null)
const router = useRouter()

const formData = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try{
        // 进行认证
        let resp = await login(formData)  
        ElMessage.success(resp.message || "登录成功")
        // 保存token
        localStorage.setItem("token",resp.data)
        router.push('/')
      }catch(error){
           ElMessage.error("登录失败！用户名或者密码错误")
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
</script>

<style scoped>
.login-container {
  background-color: #409eff;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.logo img {
  width: 100px;
  margin-bottom: 20px;
}

.el-card {
  padding: 20px;
  width: 100%;
  max-width: 400px;
}

.el-form {
  margin-top: 20px;
}

.el-button {
  width: 100%;
}
</style>